package com.yz.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author yz
 * @create 2021-11-16 22:20
 */
@Configuration
public class GuliFeignConfig {
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor(){
            @Override
            public void apply(RequestTemplate template) {
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if(attributes != null){
                    HttpServletRequest request = attributes.getRequest();
                    System.out.println("feign远程之前先进行RequestInterceptor.apply");
                    if(request != null){
                        //同步请求头数据：cookie
                        String cookie = request.getHeader("Cookie");
                        //给新请求添加cookie
                        template.header("Cookie", cookie);
                    }
                }
            }
        };
    }
}
